﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsFormsApp1.Exception;
using WindowsFormsApp1.utils;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private string sqlStr = null;
        private List<string> databaseList = null;
        private SqlConnection conn = null;
        private DataBackupUtil backupUtil = null;
        private string ipType = "local";
        private List<string> ipList = new List<string>();
        public Form1()
        {
            backupUtil = new DataBackupUtil();
            ipList = new ConfigCheck().GetIP4();
            InitializeComponent();
        }

        private void Login_Click(object sender, EventArgs e)
        {
            //判断是否为本地数据库
            if (sqlIp.Text != "." && sqlIp.Text != ipList[0].ToString())
            {
                ipType = "net";
                if (sqlIp.Text == "" || username.Text == "" || password.Text == "" || Admin.Text == "" || AdminPwd.Text == "")
                {
                    result.Text = "请将数据库IP地址，主机用户名，主机用户密码，用户名和密码填写完整!";
                    return;
                }
            }
            else
            {

                //将远程两个按钮设置为不能按
                backupdatabase_for_srever.Enabled = false;
                backuplog_for_srever.Enabled = false;
                if (sqlIp.Text == "" || username.Text == "" || password.Text == "")
                {
                    result.Text = "请将数据库IP地址，用户名和密码填写完整!";
                    return;
                }
            }
                     
            try
            {
                databaseList = new List<string>();
                string selDatabase = "select name from sys.sysdatabases where name not in ('master','msdb','tempdb','model')";
                sqlStr = "server=" + sqlIp.Text.Trim() + ";database=master;uid=" + username.Text.Trim() + ";pwd=" + password.Text.Trim();
                conn = new SqlConnection(sqlStr);
                conn.Open();
                using (SqlCommand cmd = new SqlCommand(selDatabase, conn))
                {
                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        databaseList.Add((string)reader[0]);
                    }
                    reader.Close();
                    dataBaseSet.DataSource = databaseList;
                }
                result.Text = "数据库登陆成功，请选择你想要的操作";
            }catch(System.Exception ex)
            {
                conn = null;
                result.Text = $"数据库连接失败，请检查IP地址，用户名密码是否正确 \n 原因为:{ex.Message}";
            }
        }

        private void DataBackup_Click(object sender, EventArgs e)
        {
            string message = null;
            string ipaddr = ipList[1];
            string admin = Admin.Text;
            string adminPwd = AdminPwd.Text;
            if (conn == null)
            {
                result.Text = "数据库未连接，请先进行数据库连接";
                return;
            }
            string database = dataBaseSet.SelectedItem.ToString();
            System.Diagnostics.Debug.WriteLine($"##########################正在进行的数据库为:{database}##########################");
            
            result.Text = $"{database}数据库文件正在备份中请稍等^^^^^^^^^^^^^";
            //按钮全部失效
            button_statu_change("disappear");
            //加入ip参数
            if (ipType == "net")
            {
                    
                var beginInvokeThread = new Thread(() =>
                {
                    try
                    {
                        backupUtil.DataBack(conn, database, ipaddr, admin, adminPwd);
                    }
                    catch (System.Exception ex)
                    {
                        message = ex.Message;
                    }
                });
                beginInvokeThread.Start();
                while (beginInvokeThread.IsAlive)
                {

                }
                button_statu_change("show");
            }
            else
            {
                var beginInvokeThread = new Thread(() =>
                {
                    try
                    {
                        backupUtil.DataBack(conn, database);
                    }
                    catch (System.Exception ex)
                    {
                        message = $"数据库{database}备份失败,原因为:{ex.Message}";
                    }
                });
                beginInvokeThread.Start();
                while (beginInvokeThread.IsAlive)
                {
                        
                }
                button_statu_change("show");
                backupdatabase_for_srever.Enabled = false;
                backuplog_for_srever.Enabled = false;
            }
            using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = conn;
                    LogSize_MB.Text = backupUtil.findLogSize(cmd, dataBaseSet.SelectedItem.ToString()).ToString();
                }

            if (message != null)
                result.Text = message;
            else
                result.Text = $"数据库{database}备份成功";
            System.Diagnostics.Debug.WriteLine($"##########################数据库{database}操作结束###############################");
        }

        private void Logback_Click(object sender, EventArgs e)
        {
            string message = null;
            string ipaddr = ipList[1];
            string admin = Admin.Text;
            string adminPwd = AdminPwd.Text;
            if (conn == null)
            {
                result.Text = "数据库未连接，请先进行数据库连接";
                return;
            }
            string database = dataBaseSet.SelectedItem.ToString();
            System.Diagnostics.Debug.WriteLine($"##########################正在进行的数据库为:{database}##########################");

            result.Text = $"{database}数据库日志文件正在备份中请稍等^^^^^^^^^^^^^";
            //按钮全部失效
            button_statu_change("disappear");
            float log_size = float.Parse(logSize.Text);
            if (ipType == "net")
            {
                var beginInvokeThread = new Thread(() =>
                {
                    try
                    {
                        backupUtil.LogBack(conn, database, log_size, ipaddr, admin, adminPwd);
                    }
                    catch (MyException myex)
                    {
                        message = myex.Message;
                    }
                    catch (System.Exception ex)
                    {
                        message = $"数据库{database}备份日志失败,原因为:{ex.Message}";
                    }
                });
                beginInvokeThread.Start();
                while (beginInvokeThread.IsAlive)
                {

                }
                button_statu_change("show");

            }
            else
            {
                var beginInvokeThread = new Thread(() =>
                {
                    try
                    {
                        backupUtil.LogBack(conn, database, log_size);
                    }
                    catch (MyException myex)
                    {
                        message = myex.Message;
                    }
                    catch (System.Exception ex)
                    {
                        message = $"数据库{database}备份日志失败,原因为:{ex.Message}";
                    }
                });
                beginInvokeThread.Start();
                while (beginInvokeThread.IsAlive)
                {

                }
                button_statu_change("show");
                backupdatabase_for_srever.Enabled = false;
                backuplog_for_srever.Enabled = false;
            }
                   
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.Connection = conn;
                LogSize_MB.Text = backupUtil.findLogSize(cmd, dataBaseSet.SelectedItem.ToString()).ToString();
            }
            result.Text = message;
            System.Diagnostics.Debug.WriteLine($"##########################数据库{database}操作结束###############################");
        }

        private void LogClean_Click(object sender, EventArgs e)
        {
            if (conn == null)
            {
                result.Text = "数据库未连接，请先进行数据库连接";
                return;
            }
            string database = dataBaseSet.SelectedItem.ToString();
            System.Diagnostics.Debug.WriteLine($"##########################正在进行的数据库为:{database}##########################");
            try
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = conn;
                    backupUtil.cleanDB(cmd, database);
                }
            }
            catch (MyException myex)
            {
                result.Text = myex.Message;
            }
            catch (System.Exception ex)
            {
                result.Text = $"数据库{database}清理失败,原因为:{ex.Message}";
            }
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.Connection = conn;
                LogSize_MB.Text = backupUtil.findLogSize(cmd, dataBaseSet.SelectedItem.ToString()).ToString();
            }
            System.Diagnostics.Debug.WriteLine($"##########################数据库{database}操作结束###############################");
        }

        private void reset_Click(object sender, EventArgs e)
        {
            this.logSize.Text = "16";
            this.sqlIp.Text = null;
            this.username.Text = null;
            this.password.Text = null;
            this.databaseList = null;
            this.dataBaseSet.DataSource = null;
            this.LogSize_MB.Text = null;
            this.conn = null;
            this.Admin.Text = null;
            this.AdminPwd.Text = null;
            this.databseSize.Text = null;
            backupdatabase_for_srever.Enabled = true;
            backuplog_for_srever.Enabled = true;
            this.result.Text = "重置成功, 请重新登陆你想操作的数据库";
        }


        private void button_statu_change(string flag = "show")
        {
            backupdatabase_for_srever.Enabled = flag == "disappear" ? false : true;
            backuplog_for_srever.Enabled = flag == "disappear" ? false : true;
            reset.Enabled = flag == "disappear" ? false : true;
            LogClean.Enabled = flag == "disappear" ? false : true;
            Logback.Enabled = flag == "disappear" ? false : true;
            DataBackup.Enabled = flag == "disappear" ? false : true;
            Login.Enabled = flag == "disappear" ? false : true;
        }





        private void dataBaseSet_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if(dataBaseSet.SelectedItem != null)
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        cmd.Connection = conn;
                        LogSize_MB.Text = backupUtil.findLogSize(cmd, dataBaseSet.SelectedItem.ToString()).ToString();
                        databseSize.Text = backupUtil.getDataBaseFileSize(cmd, dataBaseSet.SelectedItem.ToString()).ToString();
                    }
                }
            }catch(System.Exception ex)
            {
                result.Text = ex.Message;
            }
        }

        private void backupdatabase_for_srever_Click(object sender, EventArgs e)
        {
            string message = null;
            if (conn == null)
            {
                result.Text = "数据库未连接，请先进行数据库连接";
                return;
            }
            string database = dataBaseSet.SelectedItem.ToString();
            System.Diagnostics.Debug.WriteLine($"##########################正在进行的数据库为:{database}##########################");
            
            result.Text = $"{database}数据库文件正在备份中请稍等^^^^^^^^^^^^^";
            //按钮全部失效
            button_statu_change("disappear");
            var beginInvokeThread = new Thread(() =>
            {
                try
                {
                    backupUtil.netBackupData_createFileForServer(conn, database);
                }
                catch (System.Exception ex)
                {
                    message = $"数据库{database}备份日志失败,原因为:{ex.Message}";
                }
            });
            beginInvokeThread.Start();
            while (beginInvokeThread.IsAlive)
            {

            }
            button_statu_change("show");
            if (message != null)
                result.Text = message;
            else
                result.Text = $"数据库{database}备份成功";   
            System.Diagnostics.Debug.WriteLine($"##########################数据库{database}操作结束###############################");
        }

        private void backuplog_for_srever_Click(object sender, EventArgs e)
        {
            string message = null;
            if (conn == null)
            {
                result.Text = "数据库未连接，请先进行数据库连接";
                return;
            }
            string database = dataBaseSet.SelectedItem.ToString();
            System.Diagnostics.Debug.WriteLine($"##########################正在进行的数据库为:{database}##########################");
            result.Text = "{database}数据库日志正在备份中请稍等^^^^^^^^^^^^^";
            //按钮全部失效
            button_statu_change("disappear");
            float log_size = float.Parse(logSize.Text);
            var beginInvokeThread = new Thread(() =>
            {
                try
                {
                    backupUtil.netBackupLog_createFileForServer(conn, database, log_size);
                }
                catch (MyException myex)
                {
                    message = myex.Message;
                }
                catch (System.Exception ex)
                {
                    message = $"数据库{database}清理失败,原因为:{ex.Message}";
                }
            });
            beginInvokeThread.Start();
            while (beginInvokeThread.IsAlive)
            {

            }
            button_statu_change("show");
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.Connection = conn;
                LogSize_MB.Text = backupUtil.findLogSize(cmd, dataBaseSet.SelectedItem.ToString()).ToString();
            }
            result.Text = message;
            System.Diagnostics.Debug.WriteLine($"##########################数据库{database}操作结束###############################");
        }
    }
}
